/*
 * @Author: yangzonglong
 * @Date: 2021-05-08 14:07:56
 * @version: v1.0.0
 * @Descripttion: 表单预览
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-08-26 17:29:38
 * @Auditor:
 */
import React, { useState, useEffect, useMemo, useCallback, useRef, forwardRef, useImperativeHandle } from 'react';
import { MobileView } from './../../components/fd';
import { ViewRefProps } from './../../components/fd/interface';
import { MobileViewRefProps } from '../fd/mobileview/MobileView';
import { getForm, getLformView } from './api';

const pd = { padding: '20px' };

const LFOFM_URL = '/fd/data_view_extra';
interface FormViewProps {
  url?: string; // 具体的url
  formName?: string; // LFORM所需
  state?: string; // 流程节点线路信息，判断当前所在节点哪些字段可编辑
  formId?: string;
  taskId?: string;
  formDataId?: string;
  isLformHtml?: boolean; // 以html模式加载LFORM
  action?: string; // 指定 postMessage action
  onOk?(data?: string): any;
  disabled?: boolean; // 只对GFORM有效，LFORM 可通过isLformHtml来替代
}
export interface FormViewRefProps {
  getData(): void;
}

export default forwardRef(
  ({ url, formId, formDataId, isLformHtml, action, onOk, formName, state, taskId, disabled }: FormViewProps, ref: React.Ref<FormViewRefProps>) => {
    const lformRef = useRef<HTMLIFrameElement>(null);
    const gformRef = useRef<ViewRefProps | MobileViewRefProps>(null);
    const formEngine = useRef('');
    const [formData, setFormData] = useState('');
    const [formInfo, setFormInfo] = useState<any>({});
    const [content, setContent] = useState(''); // 表单结构

    useImperativeHandle(ref, () => ({
      async getData() {
        if (formEngine.current === 'LFORM') {
          lformRef.current?.contentWindow?.postMessage(
            {
              action: 'saveFormData',
              firstCommit: true,
            },
            '*'
          );
        } else {
          if (disabled && editFields.length === 0) return onOk?.();

          const data = await gformRef.current?.validateFields();
          console.log(data, 'data');

          if (data) onOk?.(JSON.stringify(data));
        }
      },
    }));

    const receiveMessage = useCallback(
      (event: any) => {
        const data = event.data;
        const action = data.action;

        if (action && data?.data) onOk?.(JSON.stringify(data.data));
      },
      [onOk]
    );

    useEffect(() => {
      window.addEventListener('message', receiveMessage, false);
      return () => {
        window.removeEventListener('message', receiveMessage);
      };
    }, [receiveMessage]);

    useEffect(() => {
      if (url || !formId) return;

      getForm(formId, formDataId).then(async (result) => {
        if (result.length) {
          const [form, formData] = result;

          let _content: any = null;

          if (form.formEngine === 'LFORM') {
            // 直接渲染LFORM html模式
            if (isLformHtml) {
              _content = await getLformView(
                form.content,
                typeof formData.data === 'string' && formData.data ? JSON.parse(formData.data) : formData.data
              );
            } else {
              _content = form.content;
            }
          } else {
            // gform
            _content = form.content;
          }

          formEngine.current = form.formEngine;
          setFormData(formData.data);
          setContent(_content);
          setFormInfo({ formDesc: form.formDesc, formName: form.formName });
        }
      });
    }, [url, formId, formDataId, isLformHtml]);

    const onLformLoad = useCallback(
      (e) => {
        e.target.style.height = e.target.contentWindow.document.documentElement.scrollHeight + 15 + 'px';
        lformRef.current?.contentWindow?.postMessage(
          {
            action: action || 'nodeEdit',
            trackProcessNodeTemplateDef: content,
            trackProcessNodeTemplateData: formData && typeof formData === 'string' ? JSON.parse(formData) : formData,
            formName,
            taskId,
            state,
          },
          '*'
        );
      },
      [content, action, formName, state, formData, taskId]
    );

    const onLoad = useCallback((e) => {
      e.target.style.height = e.target.contentWindow.document.documentElement.scrollHeight + 15 + 'px';
    }, []);

    // 找出在当前节点可编辑的字段
    const [editFields, hideFields] = useMemo(() => {
      if (!state) return [];

      const parseState = JSON.parse(state);
      const huilian = parseState.huilian || {};
      const curTask = huilian[taskId!];

      if (!curTask) return [];

      const lpNodes = curTask.lpNodes || [];
      const invisibleList = curTask.invisibleList || [];

      return [lpNodes.map((item: any) => item.lpKey), invisibleList.map((item: any) => item.controlId)];
    }, [state, taskId]);

    const _url = useMemo(() => {
      if (!url) return '';
      return url + (url.includes('?') ? '&hidePrintBtn=true' : '?hidePrintBtn=true');
    }, [url]);

    if (_url) {
      return <iframe className="iframe" src={_url} width="100%" height="100%" title="formview" frameBorder="0" onLoad={(e) => onLoad(e)} />;
    }

    if (isLformHtml && formEngine.current === 'LFORM') {
      return <div dangerouslySetInnerHTML={{ __html: content }}></div>;
    }

    if (formEngine.current === 'LFORM') {
      return (
        <iframe
          className="iframe"
          ref={lformRef}
          onLoad={(e) => onLformLoad(e)}
          src={LFOFM_URL}
          width="100%"
          height="100%"
          title="LFORM"
          frameBorder="0"
        />
      );
    }

    return formEngine.current === 'GFORM' ? (
      <div style={pd}>
        <MobileView
          formInfo={formInfo}
          editFields={editFields}
          hideFields={hideFields}
          data={formData ? JSON.parse(formData) : {}}
          ref={gformRef as any}
          disabled={disabled}
          structure={content ? JSON.parse(content) : {}}
        />
      </div>
    ) : null;
  }
);
